package com.fhzn.boss.context;

import com.fhzn.boss.entity.RequestData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author fhzn
 */
@Slf4j
public class RequestContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String headerLoginUser = "X-Login-User";
        String headerAppCode = "X-APP-CODE";

        String user = request.getHeader(headerLoginUser);
        String appCode = request.getHeader(headerAppCode);
        if (Objects.isNull(user)) {
            user = ServletRequestUtils.getStringParameter(request, "handler", StringUtils.EMPTY);
        }
        if (Objects.isNull(appCode)) {
            appCode = ServletRequestUtils.getStringParameter(request, "invokeAppName", StringUtils.EMPTY);
        }
        RequestContext.setRequestData(new RequestData(user, appCode));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        RequestContext.clean();
    }
}
